<?php
namespace  app\middleware;

use app\service\LoginService;
use Closure;

class SignWms{
    public  function handle($request ,\Closure $next){
        $file  = 'log.txt';//要写入文件的文件名（可以是任意文件名），如果文件不存在，将会创建一个
        $content = date('Y-m-d h:i:s',time())."\n";

        file_put_contents($file, $content,FILE_APPEND);
        $uid=$request->post('uid',0);
        $timestamp=$request->post('timestamp',0);
        $nonce=$request->post('nonce',"");
         $sign=$request->post('sign',"");

        if ($uid==0||$timestamp==0){
              returnFail(22000,"请求参数不正确");
        }
        if ($nonce==""||$sign==""){
            returnFail(22000,"请求参数不正确");

        }
        if ($timestamp<(time()-300)||$timestamp>time()+300){
              returnFail(22001,"时间戳不正确");
        }
        $redis=linkRedis(8);
        $partnerUInfo=LoginService::getApiSalt($uid);
         $api_salt=$partnerUInfo['wms_api_salt_h5'];
         //nonce 临时流水号，防止重复
         $nonceRes=$redis->get($nonce);
         if (!empty($nonceRes)){
               returnFail(22002,"请求重复");
         }
        //获取所有的请求参数
        $params= request()->param();

        // 参考文档 https://juejin.cn/post/6983864029550739463
        unset($params['sign']);
        ksort($params);

        // rsort($params,SORT_STRING);
        $paramsRes= implode($params);
       // key进行排序
        $signRes = md5($paramsRes.$api_salt);

        if ($signRes!=strtolower($sign)){
            returnFail(22003,"请求参数不正确");
        }
        $redis->set($nonce, 1,20);
        $content = date('Y-m-d h:i:s',time())."\n";

        file_put_contents($file, $content,FILE_APPEND);
        return $next($request);
    }
}